require('../../mypublic/css/common.less');
require('../../mypublic/css/index.less');

require('../../public/misc/mediaUpload/css/style.css');
require('../../public/misc/jquery.jqGrid-4.6.0/css/ui.jqgrid.css');
require('../../public/misc/jquery-ui-themes-1.11.2/humanity/jquery-ui.min.css');
require('./index.css');

require('jquery');
require('angular-ui');

var utils = require('@yunke/core/util').default;

require('../../public/misc/jquery.jqGrid-4.6.0/js/i18n/grid.locale-cn');
require('../../public/misc/mediaUpload/js/jquery.form');
require('../../public/misc/mediaUpload/js/myUpload');

require('../../public/js/myservice/side');
require('../../public/js/myservice/authorize');
require('@yunke/ad/pop1Ad1Mobile');

require('../../public/js/ueditor')
//uri to qrcode
require('@yunke/angular-ui/lib/qrcode/jquery.qrcode');
const _ = require('lodash');

var angular = require('angular');

import environment from '@yunke/environment/environment';
const apiprefix = environment.CONFIG[process.env.env].ydxs_front;

const allTenantItem = {
    item: {text: '全部', value: 'all'},
    add(xs = []) {
        xs.unshift(this.item);
        return xs;
    },
    remove(xs = []) {
        return JSON.parse(JSON.stringify(xs)).splice(0, 1);
    }
};

angular.module('app', ['ngUI']).controller('mainCtrl', [
    '$scope', '$http', function($scope, $http) {
        var currentDate = new Date();
        $scope.data = {
            showYdxs: false,
            notShowPreShow: false,
            abstract_mode: '1', //摘要模式
            abstract: '', //摘要内容
            first_visit_show: '1', //首次进入提醒
            period_visit_show: '0', //时间段内提醒
            period_start_time: utils.formatDate(currentDate, 'yyyy-MM-dd hh:mm'),
            period_end_time: utils.formatDate(new Date(currentDate.getTime() + 86400000), 'yyyy-MM-dd hh:mm'), // +1 day
            g2_period_start_time: utils.formatDate(new Date(currentDate.getTime() + 86400000), 'yyyy-MM-dd hh:mm'),
            g2_period_end_time: utils.formatDate(new Date(currentDate.getTime() + 86400000 * 2), 'yyyy-MM-dd hh:mm'), // +2 day
            tenants: []
        };

        $scope.tenants = allTenantItem.add();

        //
        $scope.uiDialogIsShow = false;

        $scope.data.showYdxs = false;
        $scope.data.notShowPreShow = false;

        //展示更多框
        const moreControlIds = ['99986', '99985', '99988', '99989', '99990', '100004'];
        const notShowPreShowIds = ['99990'];
        const abstractTxtLimitNum = 200;

        $http.get('/api/index.php?r=organization/get-org-list', {
            params: {
                id: utils.getUrlPara('id')
            }
        }).success(rs => {

            $scope.tenants = allTenantItem.add(rs.data.map(x => ({text: x.FriendlyName, value: x.Id})));

            $http.get('/api/index.php?r=/cms/article/update-edit', {
                params: {
                    id: utils.getUrlPara('id')
                }
            }).success(function (res) {
                const data = res.data;
                let result = {};

                if (utils.getUrlPara('id')) {
                    $scope.data.tenants = _.isEmpty(data.orgGuids) ? $scope.tenants.map(x => x.value) : data.orgGuids;
                } else {
                    $scope.data.tenants = $scope.tenants.map(x => x.value);
                }

                if (moreControlIds.indexOf(data.dir_id) >= 0) {
                    $scope.data.showYdxs = true;
                    result = Object.assign({}, $scope.data, data);
                } else {
                    result = Object.assign({}, data, $scope.data);
                }
                if (data.abstract_mode === '1' && data.abstract && data.abstract.length > 0) {
                    result.abstract = data.abstract.replace(/<br\/>/g, '\n').replace(/&nbsp;/g, ' ');
                }
                const countNum = abstractTxtLimitNum - result.abstract.length;
                $scope.abstractCountDown = countNum < 0 ? 0 : countNum;
                $scope.data = result;
                oriFunc(data, $scope);
            });

        });

        //目录更改
        $scope.catlogChange = function() {
            $scope.data.showYdxs = moreControlIds.indexOf($scope.selectedItem) >= 0 ? true : false;
            $scope.data.notShowPreShow = notShowPreShowIds.indexOf($scope.selectedItem) >= 0 ? true : false;
            if ($('#image_url').val().length > 0) {
                setTimeout(function() {
                    $('#image_load').css('display', 'none');
                }, 1);
            }
        };

        $scope.attractModeToImg = function() {
            if ($scope.data.abstract_mode == 2 && $('#image_url').val().length > 0) {
                setTimeout(function() {
                    $('#image_load').css('display', 'none');
                }, 1);
            }
        };

        //预览框 限制200字以内
        $scope.limitText = function() {
            if ($scope.data.abstract.length > abstractTxtLimitNum) {
                $scope.data.abstract = $scope.data.abstract.substring(0, abstractTxtLimitNum);
                $scope.abstractCountDown = 0;
            } else {
                $scope.abstractCountDown = abstractTxtLimitNum - $scope.data.abstract.length;
            }
        };

        $scope.previewer = {
            uri: '',
            init: function(dialogScope) {
                $scope.previewScope = dialogScope;
            },
            ok: function() {
                $scope.uiDialogIsShow = false;
                $scope.previewScope = null;
            }
        };

    }]);

angular.bootstrap(document, ['app']);

function oriFunc(data, $scope) {
    var op = {
        initialFrameHeight: 300
    };
    window.UEDITOR_CONFIG.toolbars = [
        [
            'fullscreen',
            'source',
            '|',
            'undo',
            'redo',
            '|',
            'bold',
            'italic',
            'underline',
            'fontborder',
            'strikethrough',
            'superscript',
            'subscript',
            'removeformat',
            'formatmatch',
            'autotypeset',
            'blockquote',
            'pasteplain',
            '|',
            'forecolor',
            'backcolor',
            'insertorderedlist',
            'insertunorderedlist',
            'selectall',
            'cleardoc',
            '|',
            'rowspacingtop',
            'rowspacingbottom',
            'lineheight',
            '|',
            'customstyle',
            'paragraph',
            'fontfamily',
            'fontsize',
            '|',
            'directionalityltr',
            'directionalityrtl',
            'indent',
            '|',
            'justifyleft',
            'justifycenter',
            'justifyright',
            'justifyjustify',
            '|',
            'touppercase',
            'tolowercase',
            '|',
            'link',
            'unlink',
            'anchor',
            '|',
            'imagenone',
            'imageleft',
            'imageright',
            'imagecenter',
            '|',
            'simpleupload',
            'insertimage',
            'emotion',
            'scrawl',
            'insertvideo',
            'music',
            'attachment',
            'map',
            'gmap',
            'insertframe',
            'insertcode',
            'webapp',
            'pagebreak',
            'template',
            'background',
            '|',
            'horizontal',
            'date',
            'time',
            'spechars',
            'snapscreen',
            'wordimage',
            '|',
            'inserttable',
            'deletetable',
            'insertparagraphbeforetable',
            'insertrow',
            'deleterow',
            'insertcol',
            'deletecol',
            'mergecells',
            'mergeright',
            'mergedown',
            'splittocells',
            'splittorows',
            'splittocols',
            'charts',
            '|',
            'print',
            'preview',
            'searchreplace',
            'help',
            'drafts'
        ]
    ];
    var editor = new UE.ui.Editor(op);
    editor.render('meEditor');

    // 图片上传
    (function() {
        $(document).ready(function() {
            var $img = $('<img/>').attr({
                src: data.image_url,
                width: '210px',
                height: '140px'
            });
            var $container = $('#preview_container');
            $container.css({
                'display': 'block'
            }).html('');

            if (data.image_url) {
                $img.appendTo($container);
                setTimeout(function() {
                    $('#image_load').css('display', 'none');
                }, 1);
            }
        }).on('click', '#image_load, .image-upload-container .controllbar .upload', function() {
            $('[role=image-upload-file-input]').val('').trigger('click');
        }).on('change', '[role=image-upload-file-input]', function() {
            var uploadForm = $('[role=image-upload-file-form]');
            uploadForm.ajaxSubmit({
                url: '/api/index.php?r=cms/article/media-edit',
                dataType: 'json',
                success: function(data, status) {
                    if (data.result) {
                        var $img = $('<img/>').attr({
                            src: data.path,
                            width: '210px',
                            height: '140px'
                        });
                        var $container = $('#preview_container');
                        $container.css({
                            'display': 'block'
                        }).html('');
                        $img.appendTo($container);
                        $('#image_load').css('display', 'none');
                        $('#image_url').val(data.path);
                    }
                }
            });
        }).on('mouseover', '.image-upload-container', function(event) {
            $('.image-upload-container .controllbar').show();
        }).on('mouseout', '.image-upload-container', function(event) {
            $('.image-upload-container .controllbar').hide();
        }).on('click', '.image-upload-container .controllbar .cancel', function(event) {
            var $container = $('#preview_container');
            $container.css({
                'display': 'none'
            }).html('');
            $('#image_url').val('');
            $('#image_load').css('display', 'block');
        });
    })();

    var article = {
        sData: function() {
            var mode = $('#abstractMode').val(),
                abstract = $('#abstract').val();
            if (mode == '1' && abstract.length > 0) {
                abstract = abstract.replace(/\n/g, '<br/>').replace(/\s/g, '&nbsp;');
            }

            var isYdxsType = $('#showYdxs').val() == 'true',
                periodVisitShow = $('#periodVisitShow').val(),
                excuteValue = {
                    'abstractMode': $('#abstractMode').val(),
                    'abstract': abstract,
                    'firstVisitShow': $('#firstVisit').val(),
                    'periodVisitShow': periodVisitShow,
                    'periodStartTime': periodVisitShow == 1 ? $('#start_date').val() : '',
                    'periodEndTime': periodVisitShow == 1 ? $('#end_date').val() : '',
                    'g2PeriodStartTime': periodVisitShow == 1 ? $('#g2_start_date').val() : '',
                    'g2PeriodEndTime': periodVisitShow == 1 ? $('#g2_end_date').val() : ''
                },
                baseValue = {
                    'title': $('#title').val(),
                    'imageUrl': $('#image_url').val(),
                    'author': $('#author').val(),
                    'tag': $('#tag').val(),
                    'linkUrl': $('#link_url').val(),
                    'fileUrl': $('#file_url').val(),
                    'fileName': $('#file_name').val(),
                    'content': UE.getEditor('meEditor').getContent(),
                    'dirId': $('#dir_id').val(),
                    'aId': $('#a_id').val(),
                    'closeTime': $('#close_time').val()
                };
            if ($scope.data.tenants.indexOf('all') === -1) {
                baseValue.orgGuids = $scope.data.tenants.filter(x => x !== 'all');
            }
            if (isYdxsType) {
                baseValue = Object.assign({}, baseValue, excuteValue);
            }
            return baseValue;
        },
        ajax: function($url, $type, $obj) {
            article.type = $type;
            $.ajax({
                url: $url,
                data: this.sData(),
                type: 'post',
                success: submitSuccess
            });

            function submitSuccess(data) {
                if (data.retMsg != null && data.retMsg != '') {
                    alert(data.retMsg);
                } else {
                    switch (article.type) {
                        case 1:
                            alert('保存成功！');
                            $('#a_id').val(data.data);
                            window.location.href = '/cms/update_list/index.html';
                            break;
                        case 2:
                            alert('保存成功！');
                            window.location.href = '/cms/update_edit/index.html';
                            break;
                        case 3:
                            alert('保存成功！');
                            window.location.href = '/cms/update_list/index.html';
                            break;
                        case 4:
                            alert('保存并复制成功！');
                            window.location.href = '/cms/update_edit/index.html?id=' + data.data;
                            break;
                        case 5:
                            var uri = apiprefix + '/main/explain/detail/' + data.data;
                            $('#qrcode').html('');
                            $('#qrcode').qrcode(uri);
                            $('.qrcode-wrap').show();
                            //utils.showDialog($('#qrcode').html());
                            break;
                        default:
                            break;
                    }
                }
            }
        },
        type: 0,
        bind: function() {

            // 不是其他
            var notQt = dirId => +dirId !== 99986 && +dirId !== 100004;

            var checkValid = function() {
                var link = $('#link_url').val();
                var dirId = $('#dir_id').val();
                // 其他目录不需要校验
                if (notQt(dirId) && !link && !UE.getEditor('meEditor').getContent()) {
                    alert('原文链接和正文最少填写一个');
                    return false;
                }
                if (article.sData().periodVisitShow == 1 && !($('#start_date').val() && $('#end_date').val() &&
                    $('#g2_start_date').val() && $('#g2_end_date').val())) {
                    alert('请填写G0、G2时间');
                    return false;
                }
                return true;
            };

            $('.ui-dialog-close').bind('click', function() {
                $('.qrcode-wrap').hide();
            });

            $('#preShow').bind('click', function() {
                if (!!checkValid()) {
                    var sData = article.sData();
                    var data = {
                        'title': sData.title,
                        'abstract_mode': sData.abstractMode,
                        'abstract': sData.abstractMode == 1 ? sData.abstract : sData.imageUrl,
                        'first_visit_show': '0',
                        'period_visit_show': '0',
                        'period_start_time': sData.periodStartTime,
                        'period_end_time': sData.periodEndTime,
                        'g2_period_start_time': sData.g2PeriodStartTime,
                        'g2_period_end_time': sData.g2PeriodEndTime,
                        'link_url': sData.linkUrl,
                        'content': sData.content
                    };

                    if (!data.abstract || data.abstract.length == 0) {
                        alert('没有内容要预览');
                        return;
                    }
                    var $div = $(`<div>`).addClass('update_preview_div');
                    $div.appendTo('body');

                    data.link_url = 'javascript:;';
                    window.POP_1AD1_Mobile_UPDATE_IMPL(data, {
                        container: $div[0],
                        close: function() {
                            $div[0].remove();
                        }
                    });
                }
            });
            $('#save').bind('click', function() {
                if (!!checkValid()) {
                    article.ajax('/api/index.php?r=/cms/article/save&from=update', 1);
                }
            });
            $('#save_preview').bind('click', function() {
                if (!!checkValid()) {
                    article.ajax('/api/index.php?r=/cms/article/save&from=update', 5);
                }
            });
            $('#save_create').bind('click', function() {
                if (!!checkValid()) {
                    article.ajax('/api/index.php?r=/cms/article/save&from=update', 2);
                }
            });
            $('#save_close').bind('click', function() {
                if (!!checkValid()) {
                    article.ajax('/api/index.php?r=/cms/article/save&from=update', 3);
                }
            });
            $('#save_copy').bind('click', function() {
                if (!!checkValid()) {
                    article.ajax('/api/index.php?r=/cms/article/save&copy=1&from=update', 4);
                }
            });
            $('#no_save').bind('click', function() {
                window.location.href = '/cms/update_list/index.html';
            });
        }
    };
    article.bind();
    $('#meEditor').html(data.content);

    $('.del').click(function() {
        $.ajax({
            url: '/api/index.php?r=/cms/article/fujian-del&a_id=' + data.a_id + '&url=' + $(this).attr('value'),
            type: 'GET',
            success: function(data) {
                history.go(0);
            }
        });
    });
}
